package biz.datalk.industrialland.admin.modules.system.service.impl;

import biz.datalk.industrialland.admin.component.shiro.CustomLoginUser;
import biz.datalk.industrialland.admin.modules.system.mapper.ISysDictItemExtMapper;
import biz.datalk.industrialland.admin.modules.system.operator.SysDictAndItemCacheManager;
import biz.datalk.industrialland.admin.modules.system.pojo.dto.SysDictItemDTO;
import biz.datalk.industrialland.admin.modules.system.service.ISysDictItemService;
import biz.datalk.industrialland.admin.modules.util.ShiroUtil;
import biz.datalk.industrialland.common.def.CommonConstant;
import biz.datalk.industrialland.common.def.enums.DBYNEnum;
import biz.datalk.industrialland.common.exception.ServiceException;
import biz.datalk.industrialland.common.result.UnifyResult;
import biz.datalk.industrialland.common.result.UnifyResultCode;
import biz.datalk.industrialland.common.util.EntityIdUtils;
import biz.datalk.industrialland.common.util.I18NUtil;
import biz.datalk.industrialland.mbg.mapper.SysDictItemMapper;
import biz.datalk.industrialland.mbg.pojo.po.SysDictItem;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Priority;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author tarofang@163.com
 * @date 2019-12-23
 */
@Slf4j
@Service("sysDictItemServiceBasicImpl")
@Priority(CommonConstant.INITIAL_PRIORITY)
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class SysDictItemServiceBasicImpl implements ISysDictItemService {

    private final SysDictItemMapper sysDictItemMapper;
    private final ISysDictItemExtMapper sysDictItemExtMapper;
    private final SysDictAndItemCacheManager sysDictAndItemCacheManager;

    @Autowired
    public SysDictItemServiceBasicImpl(
            SysDictItemMapper sysDictItemMapper, //
            ISysDictItemExtMapper sysDictItemExtMapper, //
            SysDictAndItemCacheManager sysDictAndItemCacheManager) {
        this.sysDictItemMapper = sysDictItemMapper;
        this.sysDictItemExtMapper = sysDictItemExtMapper;
        this.sysDictAndItemCacheManager = sysDictAndItemCacheManager;
    }

    @Override
    public UnifyResult list(SysDictItemDTO sysDictItemDTO) {
        QueryWrapper<SysDictItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc(SysDictItem.COL_ITEM_ORDER);
        queryWrapper.eq(SysDictItem.COL_DICT_ID, sysDictItemDTO.getDictId().trim());
        queryWrapper.eq(StringUtils.isNotBlank(sysDictItemDTO.getIsValid()), SysDictItem.COL_IS_VALID, StringUtils.trim(sysDictItemDTO.getIsValid()));
        queryWrapper.like(StringUtils.isNotBlank(sysDictItemDTO.getItemText()), SysDictItem.COL_ITEM_TEXT, StringUtils.trim(sysDictItemDTO.getItemText()));

        IPage<SysDictItem> page = new Page<>(sysDictItemDTO.getPageNumber(), sysDictItemDTO.getPageSize());
        IPage<SysDictItem> pageInfo = sysDictItemMapper.selectPage(page, queryWrapper);

        return UnifyResult.success().mapData().put("rows", pageInfo.getRecords()).put("total", pageInfo.getTotal());
    }

    @Override
    public UnifyResult add(SysDictItemDTO sysDictItemDTO) {

        CustomLoginUser customLoginUser = ShiroUtil.currentLoginUser();
        Date now = new Date();
        SysDictItem sysDictItem = new SysDictItem();
        sysDictItem.setDictId(sysDictItemDTO.getDictId());
        sysDictItem.setItemText(sysDictItemDTO.getItemText());
        sysDictItem.setItemValue(sysDictItemDTO.getItemValue());
        sysDictItem.setDescription(sysDictItemDTO.getDescription());
        sysDictItem.setItemOrder(sysDictItemDTO.getItemOrder());
        sysDictItem.setIsValid(DBYNEnum.Y.name());
        sysDictItem.setIsDelete(DBYNEnum.N.name());
        sysDictItem.setCreateBy(customLoginUser.getId());
        sysDictItem.setCreateName(customLoginUser.getRealname());
        sysDictItem.setCreateTime(now);
        sysDictItem.setUpdateBy(0L);
        sysDictItem.setUpdateName(StringUtils.EMPTY);
        sysDictItem.setUpdateTime(now);

        sysDictItemMapper.insertSelective(sysDictItem);
        sysDictAndItemCacheManager.removeSysDictItemCacheGroup(sysDictItemDTO.getDictId(), null);
        return UnifyResult.success();
    }

    @Override
    public UnifyResult edit(SysDictItemDTO sysDictItemDTO) {
        Long id = sysDictItemDTO.getId();
        SysDictItem exists = sysDictItemMapper.selectById(id);
        if (exists == null) {
            return UnifyResult.fail(UnifyResultCode.SERVICE_ERROR, "字典项不存在或已被删除");
        }

        CustomLoginUser customLoginUser = ShiroUtil.currentLoginUser();
        SysDictItem sysDictItem = new SysDictItem();
        sysDictItem.setId(exists.getId());
        sysDictItem.setDictId(sysDictItemDTO.getDictId());
        sysDictItem.setItemText(sysDictItemDTO.getItemText());
        sysDictItem.setItemValue(sysDictItemDTO.getItemValue());
        if (StringUtils.isNotBlank(sysDictItemDTO.getDescription())) {
            sysDictItem.setDescription(sysDictItemDTO.getDescription());
        }
        sysDictItem.setItemOrder(sysDictItemDTO.getItemOrder());
        sysDictItem.setIsValid(sysDictItemDTO.getIsValid());
        // sysDictItem.setIsDelete(sysDictItemDTO.getIsDelete());
        sysDictItem.setUpdateBy(customLoginUser.getId());
        sysDictItem.setUpdateName(customLoginUser.getRealname());
        sysDictItem.setUpdateTime(new Date());

        sysDictItemMapper.updateByPrimaryKeySelective(sysDictItem);
        sysDictAndItemCacheManager.removeSysDictItemCacheGroup(sysDictItemDTO.getDictId(), null);
        return UnifyResult.success();
    }

    @Override
    public UnifyResult delete(SysDictItemDTO sysDictItemDTO) {
        CustomLoginUser customLoginUser = ShiroUtil.currentLoginUser();
        Long id = sysDictItemDTO.getId();
        if (id == null || id <= 0L) {
            log.warn("Invalid id. [id={}]", id);
            return UnifyResult.fail("数据不存在或已被删除");
        }
        SysDictItem exists = sysDictItemMapper.selectById(id);
        if (exists == null) {
            log.warn("Invalid id, exists is null. [id={}]", id);
            return UnifyResult.fail("数据不存在或已被删除");
        }
        SysDictItem sysDictItem = new SysDictItem();
        sysDictItem.setId(id);
        // sysDictItem.setDictId(sysDictItemDTO.getDictId());
        sysDictItem.setIsDelete(DBYNEnum.Y.name());
        // sysDictItem.setIsValid(DBYNEnum.N.name());
        sysDictItem.setUpdateBy(customLoginUser.getId());
        sysDictItem.setUpdateName(customLoginUser.getRealname());
        sysDictItem.setUpdateTime(new Date());
        int resInt = sysDictItemMapper.updateByPrimaryKeySelective(sysDictItem);
        if (resInt != 1) {
            throw new ServiceException(I18NUtil.getMsg("sysdictitem.delete.fail"));
        }
        sysDictAndItemCacheManager.removeSysDictItemCacheGroup(exists.getDictId(), null);
        return UnifyResult.success();
    }

    @Override
    public UnifyResult batchDelete(SysDictItemDTO sysDictItemDTO) {
        List<Long> sysids = EntityIdUtils.parseIds(sysDictItemDTO.getSysids());
        if (CollectionUtils.isEmpty(sysids)) {
            log.debug("Invalid sysids");
            return UnifyResult.fail(I18NUtil.getMsg("sysdictitem.no.exists.or.delete"));
        }

        CustomLoginUser customLoginUser = ShiroUtil.currentLoginUser();
        SysDictItem params = new SysDictItem();
        params.setIsDelete(DBYNEnum.Y.name());
        params.setIsValid(DBYNEnum.N.name());
        params.setUpdateBy(customLoginUser.getId());
        params.setUpdateName(customLoginUser.getRealname());
        params.setUpdateTime(new Date());

        UpdateWrapper<SysDictItem> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in(SysDictItem.COL_ID, sysids);

        int resInt = sysDictItemMapper.update(params, updateWrapper);
        if (resInt != CollectionUtils.size(sysids)) {
            throw new ServiceException(I18NUtil.getMsg("sysdictitem.batch.delete.fail"));
        }

        sysDictAndItemCacheManager.batchRemoveSysDictItemCacheGroup(sysDictItemExtMapper.getDictIdByItemIdList(sysids), null);
        return UnifyResult.success();
    }

    @Override
    public UnifyResult restDel(SysDictItemDTO sysDictItemDTO) {
        Long id = sysDictItemDTO.getId();
        id = Optional.ofNullable(id).orElse(0L);
        SysDictItem exists = sysDictItemMapper.selectById(id);
        if (exists == null) {
            log.warn("The SysDictItem no exists. [id={}]", id);
            return UnifyResult.fail(UnifyResultCode.SERVICE_ERROR, "数据不存在或已被删除");
        }

        CustomLoginUser customLoginUser = ShiroUtil.currentLoginUser();
        SysDictItem sysDictItem = new SysDictItem();
        sysDictItem.setId(exists.getId());
        sysDictItem.setIsDelete(DBYNEnum.N.name());
        sysDictItem.setUpdateBy(customLoginUser.getId());
        sysDictItem.setUpdateName(customLoginUser.getRealname());
        sysDictItem.setUpdateTime(new Date());
        int resInt = sysDictItemMapper.updateByPrimaryKeySelective(sysDictItem);
        if (resInt != 1) {
            throw new ServiceException(I18NUtil.getMsg("sysdictitem.restdel.fail"));
        }
        sysDictAndItemCacheManager.removeSysDictItemCacheGroup(exists.getDictId(), null);
        return UnifyResult.success();
    }
}
